﻿using Group3.MediaTool.Interface;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Group3.MediaTool.Core.ObjectGenerator;

namespace Group3.MediaTool.OWIN.Model
{
    /// <summary>
    /// Represents an object, that was specified in an web-interface and serialized as jsonString
    /// </summary>
    public class ObjectWebDefinition : IObjectWebDefinition
    {
        public string OrmName { get; set; }
        public string Definitions { get; set; }
        public IObjectDefinition ToIObjectDefinition()
        {
            try
            {
                string[] stringArray = (string[])JsonConvert.DeserializeObject(this.Definitions, typeof(string[]));
                if (stringArray != null)
                {
                    IObjectDefinition obj = new ObjectDefinition() { OrmName = this.OrmName };
                    obj.DataFields = GetFieldDefinitions(stringArray);
                    return obj;
                }
            }
            catch
            {

            }
            return null;
        }
        private IEnumerable<IFieldDefinition> GetFieldDefinitions(string[] data)
        {
            foreach (string fieldWebDefinition in data)
            {
                IFieldWebDefinition def = (FieldWebDefinition)JsonConvert.DeserializeObject(fieldWebDefinition, typeof(FieldWebDefinition));
                yield return def.ToIFieldDefinition();
            }
        }
    }
}
